document.write('<link type="text/css" rel="stylesheet" href="' + context
		+ '/app/cell/css/sellist.css"/>');

var pageSize = 15;

/**
 * 标段选择
 * 
 * @param {}
 *            combolabel
 * @param {}
 *            returnIdField
 * @param {}
 *            returnNameField
 * @param {}
 *            defaultValue
 * @param {}
 *            allowBlank
 * @return {}
 */
function sellist(combolabel, returnIdField, returnNameField, returnBDIdField,
		returnBDNameField, defaultValue, allowBlank, userid) {
	var comboxid = returnIdField + '_';

	var comboWithTooltip = new Ext.form.ComboBox({
				store : new Ext.data.SimpleStore({
							fields : [],
							data : [[]]
						}),
				fieldLabel : combolabel,
				editable : false,
				id : comboxid,
				name : comboxid,
				mode : 'local',
				triggerAction : 'all',
				listWidth : 600,
				maxHeight : 400,
				tpl : '<div id="cellComboListArea"></div>',
				selectedClass : '',
				onSelect : Ext.emptyFn,
				allowBlank : (allowBlank == true),
				emptyText : '请选择...'
			});

	var cellListStore = new Ext.data.JsonStore({
				idProperty : 'id',
				remoteSort : false,
				totalProperty : 'totalCount',
				root : 'queryList',
				fields : ['PAGINATION_NUMBER', 'C_ID', 'C_NAME', 'C_UNIT',
						'C_TYPE', 'C_AREA', 'CB_ID', 'CB_NAME'],

				// load using script tags for cross domain, if the data in on
				// the same domain as
				// this page, an HttpProxy would be better
				proxy : new Ext.data.ScriptTagProxy({
							url : context
									+ '/app/cellaction.do?method=sellist&userid='
									+ userId
						})
			});

	var cellListGrid = new Ext.grid.GridPanel({
				id : 'cellListGrid',
				title : '设计单元-标段列表',
				store : cellListStore,
				columns : [{
							header : '设计单元',
							width : 200,
							sortable : true,
							dataIndex : 'C_NAME'
						}, {
							header : '建管单位',
							width : 150,
							sortable : true,
							dataIndex : 'C_UNIT'
						}, {
							header : '建管模式',
							width : 100,
							sortable : true,
							dataIndex : 'C_TYPE'
						}, {
							header : '行政区域',
							width : 150,
							sortable : true,
							dataIndex : 'C_AREA'
						}, {
							header : '标段名称',
							width : 150,
							sortable : true,
							dataIndex : 'CB_NAME',
							renderer : renderBDHeader
						}],
				stripeRows : true,
				autoExpandColumn : 'C_NAME',
				region : 'center',
				layout : 'fit',
				height : 250,
				border : false,
				viewConfig : {
					forceFit : true
				},
				// config options for stateful behavior
				stateful : true,
				stateId : 'grid',
				loadMask : {
					msg : "数据加载中，请稍等..."
				},
				bbar : new Ext.PagingToolbar({
							pageSize : pageSize,// 每页显示的记录值
							store : cellListStore,
							displayInfo : true,
							displayMsg : '总记录数 {0} - {1} of {2}',
							emptyMsg : "没有记录"
						}),
				listeners : {
					rowclick : function(grid, rowIndex, e) {
						var record = grid.getStore().getAt(rowIndex);

						var name = record.data.C_NAME + ' : '
								+ record.data.CB_NAME;

						/* 设计单元ID */
						var id = record.data.C_ID;
						/* 设计单元名称 */
						var cellname = record.data.C_NAME;
						/* 标段ID */
						var bdid = record.data.CB_ID;
						/* 标段名称 */
						var bdname = record.data.CB_NAME;

						comboWithTooltip.setValue(name);
						if (Ext.getCmp(returnIdField)) {
							Ext.getCmp(returnIdField).setValue(id);

						}

						if (Ext.getCmp(returnNameField)) {
							Ext.getCmp(returnNameField).setValue(cellname);
						}

						if (Ext.getCmp(returnBDIdField)) {
							Ext.getCmp(returnBDIdField).setValue(bdid);

						}

						if (Ext.getCmp(returnBDNameField)) {
							Ext.getCmp(returnBDNameField).setValue(bdname);
						}

						comboWithTooltip.collapse();
					}
				}
			});

	comboWithTooltip.on('expand', function() {
		cellListGrid.render('cellComboListArea');
		cellListStore.load({
					params : {
						start : 0,
						limit : pageSize
					},
					callback : function(r, options, success) {
						if (success == false) {
							Ext.Msg.alert('ERROR', '加载数据出现异常.');
						} else {
							var total = cellListGrid.getStore().getCount();// 数据行数

							var arr = [];
							for (var j = 0; j < total; j++) {
								var record = cellListGrid.getStore().getAt(j);
								if (hasSelected(Ext.getCmp(returnIdField)
												.getValue(), record.data.C_ID)) {
									arr.push(record);
								}
							}
							if (arr.length > 0) {
								cellListGrid.getSelectionModel()
										.selectRecords(arr);
							}
						}
					}
				});
	});

	return comboWithTooltip;
}

function renderBDHeader(value, cellmeta, record, rowIndex, columnIndex, store) {
	var str = value;

	if (value.indexOf(',') > -1) {
		str = '';
		var names = value.split(",");

		for (var i = 0; i < names.length; i++) {
			if (names[i] != '') {
				str += names[i] + '<br/>';
			}
		}
	}

	return str;
}

function renderBD4ChkHeader(value, cellmeta, record, rowIndex, columnIndex,
		store) {
	var str = value;

	if (value != '') {
		str = '';
		var names = value.split(",");
		var ids = record.data['CB_ID'].split(",");

		for (var i = 0; i < names.length; i++) {
			if (names[i] != '') {
				str += '<input type="checkbox" name="chk" id="chk'
						+ ids[i]
						+ '" value="'
						+ ids[i]
						+ '" cellName="'
						+ record.data['C_NAME']
						+ '" bdName="'
						+ names[i]
						+ '" item="bdchk" cell="'
						+ record.data['C_ID']
						+ '" onclick="javascript:checkMe(this);" style="vertical-align:middle;"> '
						+ names[i] + '<br/>';
			}
		}
	}

	return str;
}

/**
 * 
 * @param {}
 *            thizz
 */
function checkMe(thizz) {
	if (thizz.checked) {
		var items = A('item', 'bdchk');
		if (items != null && items.length > 0) {
			for (var i = 0; i < items.length; i++) {
				if (items[i].getAttribute('cell') != thizz.getAttribute('cell')) {
					items[i].checked = false;
				}
			}
		}
	}
}

/**
 * 标段选择
 * 
 * @param {}
 *            combolabel
 * @param {}
 *            returnIdField
 * @param {}
 *            returnNameField
 * @param {}
 *            defaultValue
 * @param {}
 *            allowBlank
 * @return {}
 */
function querysellist(combolabel, returnIdField, returnNameField, defaultValue,
		allowBlank) {
	var comboxid = returnIdField + '_';

	var comboWithTooltip = new Ext.form.ComboBox({
				store : new Ext.data.SimpleStore({
							fields : [],
							data : [[]]
						}),
				fieldLabel : combolabel,
				editable : false,
				id : comboxid,
				name : comboxid,
				mode : 'local',
				triggerAction : 'all',
				listWidth : 600,
				maxHeight : 400,
				tpl : '<div id="cellComboListArea"></div>',
				selectedClass : '',
				onSelect : Ext.emptyFn,
				allowBlank : (allowBlank == true),
				emptyText : '请选择...'
			});

	var cellListStore = new Ext.data.JsonStore({
				idProperty : 'CB_ID',
				remoteSort : false,
				totalProperty : 'totalCount',
				root : 'queryList',
				fields : ['PAGINATION_NUMBER', 'C_ID', 'C_NAME', 'C_UNIT',
						'C_TYPE', 'C_AREA', 'CB_ID', 'CB_NAME'],

				// load using script tags for cross domain, if the data in on
				// the same domain as
				// this page, an HttpProxy would be better
				proxy : new Ext.data.ScriptTagProxy({
							url : context
									+ '/app/cellaction.do?method=querysellist'
						})
			});

	cellListStore.on('load', function(store, records, options) {
				var arr = [];
				for (var i = 0; i < records.length; i++) {
					var record = records[i];
					var isMatch = hasSelected(Ext.getCmp(returnIdField)
									.getValue(), record.data.C_ID);
					if (isMatch) {
						arr.push(record);
					}
				}
				cellListGrid.getSelectionModel().selectRecords(arr);
			}, this, {
				delay : 1000
			})

	var cellListGrid = new Ext.grid.GridPanel({
				id : 'cellListGrid',
				title : '设计单元-标段列表',
				store : cellListStore,
				columns : [{
							header : '设计单元',
							width : 200,
							sortable : true,
							dataIndex : 'C_NAME'
						}, {
							header : '建管单位',
							width : 150,
							sortable : true,
							dataIndex : 'C_UNIT'
						}, {
							header : '建管模式',
							width : 100,
							sortable : true,
							dataIndex : 'C_TYPE'
						}, {
							header : '行政区域',
							width : 150,
							sortable : true,
							dataIndex : 'C_AREA'
						}, {
							header : '标段名称',
							width : 150,
							sortable : true,
							dataIndex : 'CB_NAME',
							renderer : renderBDHeader
						}],
				stripeRows : true,
				autoExpandColumn : 'C_NAME',
				region : 'center',
				layout : 'fit',
				height : 250,
				border : false,
				viewConfig : {
					forceFit : true
				},
				// config options for stateful behavior
				stateful : true,
				stateId : 'grid',
				loadMask : {
					msg : "数据加载中，请稍等..."
				},
				bbar : new Ext.PagingToolbar({
							pageSize : pageSize,// 每页显示的记录值
							store : cellListStore,
							displayInfo : true,
							displayMsg : '总记录数 {0} - {1} of {2}',
							emptyMsg : "没有记录"
						}),
				listeners : {
					rowclick : function(grid, rowIndex, e) {
						var record = grid.getStore().getAt(rowIndex);

						var name = record.data.C_NAME + ' : '
								+ record.data.CB_NAME;

						var id = record.data.C_ID;

						comboWithTooltip.setValue(name);
						if (Ext.getCmp(returnIdField)) {
							Ext.getCmp(returnIdField).setValue(id);

						}

						if (Ext.getCmp(returnNameField)) {
							Ext.getCmp(returnNameField).setValue(name);
						}

						comboWithTooltip.collapse();
					}
				}
			});

	comboWithTooltip.on('expand', function() {
				cellListGrid.render('cellComboListArea');
				cellListStore.load({
							params : {
								start : 0,
								limit : pageSize
							},
							callback : function(r, options, success) {
								if (success == false) {
									Ext.Msg.alert('ERROR', '加载数据出现异常.');
								} else {

								}
							}
						});
			});

	return comboWithTooltip;
}

/**
 * 标段选择
 * 
 * @param {}
 *            combolabel
 * @param {}
 *            returnIdField
 * @param {}
 *            returnNameField
 * @param {}
 *            defaultValue
 * @param {}
 *            allowBlank
 * @return {}
 */
function bdsellist(combolabel, returnIdField, returnNameField, defaultValue,
		allowBlank) {
	var comboxid = returnIdField + '_';

	var comboWithTooltip = new Ext.form.ComboBox({
				store : new Ext.data.SimpleStore({
							fields : [],
							data : [[]]
						}),
				fieldLabel : combolabel,
				editable : false,
				id : comboxid,
				name : comboxid,
				mode : 'local',
				triggerAction : 'all',
				listWidth : 600,
				maxHeight : 400,
				tpl : '<div id="cellComboListArea"></div>',
				selectedClass : '',
				onSelect : Ext.emptyFn,
				allowBlank : (allowBlank == true),
				emptyText : '请选择...'
			});

	var cellListStore = new Ext.data.JsonStore({
				idProperty : 'CB_ID',
				remoteSort : false,
				totalProperty : 'totalCount',
				root : 'queryList',
				fields : ['PAGINATION_NUMBER', 'C_ID', 'C_NAME', 'C_UNIT',
						'C_TYPE', 'C_AREA', 'CB_ID', 'CB_NAME'],

				// load using script tags for cross domain, if the data in on
				// the same domain as
				// this page, an HttpProxy would be better
				proxy : new Ext.data.ScriptTagProxy({
							url : context + '/app/cellaction.do?method=alllist'
						})
			});

	cellListStore.on('load', function(store, records, options) {
				var arr = [];
				for (var i = 0; i < records.length; i++) {
					var record = records[i];
					var isMatch = hasChecked(Ext.getCmp(returnIdField)
									.getValue(), record);
					if (isMatch) {
						arr.push(record);
					}
				}
				cellListGrid.getSelectionModel().selectRecords(arr);
			}, this, {
				delay : 1000
			})

	var cellListGrid = new Ext.grid.GridPanel({
				id : 'cellListGrid',
				title : '设计单元-标段列表',
				store : cellListStore,
				columns : [{
							header : '设计单元',
							width : 200,
							sortable : true,
							dataIndex : 'C_NAME'
						}, {
							header : '建管单位',
							width : 150,
							sortable : true,
							dataIndex : 'C_UNIT'
						}, {
							header : '建管模式',
							width : 100,
							sortable : true,
							dataIndex : 'C_TYPE'
						}, {
							header : '行政区域',
							width : 150,
							sortable : true,
							dataIndex : 'C_AREA'
						}, {
							header : '标段名称',
							width : 150,
							sortable : true,
							dataIndex : 'CB_NAME',
							renderer : renderBD4ChkHeader
						}],
				stripeRows : true,
				autoExpandColumn : 'C_NAME',
				region : 'center',
				layout : 'fit',
				height : 250,
				border : false,
				viewConfig : {
					forceFit : true
				},
				// config options for stateful behavior
				stateful : true,
				stateId : 'grid',
				loadMask : {
					msg : "数据加载中，请稍等..."
				},
				tbar : new Ext.Toolbar({
							autoWidth : true,
							autoShow : true,
							items : [{
								iconCls : 'ok',
								text : ' 确定 ',
								handler : function() {
									var items = A('item', 'bdchk');
									var cellName = '';
									var ids = '';
									var names = '';
									if (items.length > 0) {
										for (var i = 0; i < items.length; i++) {
											if (items[i].checked) {
												cellName = items[i]
														.getAttribute('cellName');

												ids += items[i].value + ',';
												names += items[i]
														.getAttribute('bdName')
														+ ',';
											}
										}

										ids = ids.substring(0, ids.length - 1);
										names = names.substring(0, names.length
														- 1);
										if (ids != '') {
											names = cellName + ' : ' + names;
										}
									}

									comboWithTooltip.setValue(names);
									if (Ext.getCmp(returnIdField)) {
										Ext.getCmp(returnIdField).setValue(ids);

									}

									if (Ext.getCmp(returnNameField)) {
										Ext.getCmp(returnNameField)
												.setValue(names);
									}

									comboWithTooltip.collapse();
								}
							}]
						}),
				bbar : new Ext.PagingToolbar({
							pageSize : pageSize,// 每页显示的记录值
							store : cellListStore,
							displayInfo : true,
							displayMsg : '总记录数 {0} - {1} of {2}',
							emptyMsg : "没有记录"
						})
			});

	comboWithTooltip.on('expand', function() {
				cellListGrid.render('cellComboListArea');
				cellListStore.load({
							params : {
								start : 0,
								limit : pageSize
							},
							callback : function(r, options, success) {
								if (success == false) {
									Ext.Msg.alert('ERROR', '加载数据出现异常.');
								} else {

								}
							}
						});
			});

	return comboWithTooltip;
}

function hasSelected(ids, recordId) {
	var r = false;
	var idstr = ids.split(',');
	for (var i = 0; i < idstr.length; i++) {
		if (idstr[i] == recordId) {
			r = true;
			break;
		}
	}
	return r;
}

function hasChecked(ids, record) {
	var rnt = false;
	var idstr = record.data['CB_ID'].split(",");

	for (var i = 0; i < idstr.length; i++) {
		if (idstr[i] != '' && idInids(idstr[i], ids)) {
			$('chk' + idstr[i]).checked = true;
			rnt = true;
		}
	}
	return rnt;
}

function idInids(id, ids) {
	var rnt = false;
	var idstr = ids.split(",");
	for (var i = 0; i < idstr.length; i++) {
		if (id == idstr[i]) {
			rnt = true;
			break;
		}
	}
	
	return rnt;
}